/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.admin;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.LoginService;
import model.User;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Thai Dac Vinh
 */
public class LoginStrutsAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            String user_name = request.getParameter("username");
            String password = request.getParameter("password");
            String remember = request.getParameter("remember");
            LoginService loginService = new LoginService();
            User user = loginService.checkLogin(user_name, password);
            if (user != null) {
                HttpSession session = request.getSession();
                int expiry = -1;
                if ((remember != null) && (remember.equals("checked"))) {
                    expiry = 60 * 60 * 24 * 7; // 7 days
                }
                Cookie user_name_cookie = new Cookie("userName", user_name);
                Cookie password_cookie = new Cookie("password", password);
                Cookie remember_cookie = new Cookie("remember", remember);
                user_name_cookie.setMaxAge(expiry);
                password_cookie.setMaxAge(expiry);
                remember_cookie.setMaxAge(expiry);
                response.addCookie(user_name_cookie);
                response.addCookie(password_cookie);
                response.addCookie(remember_cookie);
                session.setAttribute("user", user);
                return mapping.findForward(SUCCESS);
            }
        } catch (Exception e) {
            System.err.println(e);
        }
        request.setAttribute("errorMsg", "Login Fail. Please check your User name and Password!");
        return mapping.findForward("admin_login");
    }
}
